import os
import re
import datetime
import configparser
import logging
from config.settings import SCHEMA_FILE_ADR,SCHEMA_FILE_IOS

__author__ = 'weixin.yuan'
logger = logging.getLogger('train')


class Schema(object):
    def __init__(self, schema_file, tag):
        self.schema_file = schema_file
        self.tag = tag

    def __write_schema_adr(self):
        with open(self.schema_file, mode='r+', encoding='utf-8') as f:
            content = f.readlines()

        new_content = []
        for line in content:
            pattern = re.compile(r'(\d{4}-\d{2}-\d{2})')
            today = datetime.date.today()
            tomorrow = today + datetime.timedelta(days=3)
            out = re.sub(pattern, str(tomorrow), line)
            new_content.append(out)

        with open(self.schema_file, mode='w', encoding='utf-8') as f:
            for line in new_content:
                f.write(line)
        return 0
        # return os.system('adb push ' + self.schema_file + ' /storage/emulated/0/schemaurls.txt')

    def __write_schema_ios(self):
        conf = configparser.ConfigParser()
        conf.read(self.schema_file)
        options = conf.options('ios')
        for option in options:
            value = conf.get('ios', option)
            pattern = re.compile(r'(\d{4}-\d{2}-\d{2})')
            today = datetime.date.today()
            tomorrow = today + datetime.timedelta(days=3)
            new_value = re.sub(pattern, str(tomorrow), value)
            conf.set('ios', option, new_value)
            conf.write(open(self.schema_file, "wb"))
        return 0

    def run(self):
        if self.tag == 'ios':
            status = self.__write_schema_ios()
        else:
            status = self.__write_schema_adr()
        if status == 0:
            msg = 'success'
            logger.info('schema文件替换成功')
        else:
            msg = 'failed'
        return msg


if __name__ == '__main__':
    Schema(SCHEMA_FILE_ADR, 'anr').run()
